package com.itjiange.shopsystem.service;

import com.itjiange.shopsystem.pojo.UserInfo;
import com.itjiange.shopsystem.repo.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 用户业务层
 *
 * @author ItJiange
 * @date 2023/11/18
 */
@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    public String login(String account, String password) {
        UserInfo userInfo = userRepository.findByUserNameAndUserPassword(account, password);
        if (userInfo == null) {
            return "account / userPassword is ERROR";
        }
        return "Login Success";
    }

    public String register(UserInfo userInfo) {
        if (checkUserExists(userInfo.getUserName())) {
            throw new RuntimeException("User already registered");
        }
        userInfo.setCreateDate(new Date());
        userRepository.save(userInfo);
        return "Register Success";
    }

    /**
     * 判断是否已有登录用户
     * @param userName
     * @return
     */
    public boolean checkUserExists(String userName) {
        // 查询是否存在重复用户
        UserInfo userInfo = userRepository.findByUserName(userName);
        if (userInfo != null) {
            return true;
        }
        return false;
    }
}
